import React, { useEffect, useState } from "react";
import "./Watermark.css";

const getRandomPosition = (width, height) => {
	const top = Math.random() * (height - 50); // 50是水印的高度
	const left = Math.random() * (width - 200); // 200是水印的宽度
	return { top, left };
};

const isOverlapping = (newPos, positions) => {
	for (let pos of positions) {
		if (!(newPos.left + 200 < pos.left || newPos.left > pos.left + 200 || newPos.top + 50 < pos.top || newPos.top > pos.top + 50)) {
			return true;
		}
	}
	return false;
};

const Watermark = () => {
	const [positions, setPositions] = useState([]);

	useEffect(() => {
		const width = window.innerWidth;
		const height = window.innerHeight;
		const newPositions = [];
		const watermarks = [];

		while (watermarks.length < 10) {
			const pos = getRandomPosition(width, height);
			if (!isOverlapping(pos, newPositions)) {
				newPositions.push(pos);
				watermarks.push(
					<div key={watermarks.length} className="watermark" style={{ top: pos.top, left: pos.left }}>
						{sessionStorage.getItem("sname")}
					</div>,
				);
			}
		}

		setPositions(newPositions);
	}, []);

	return (
		<div className="watermark-container">
			{positions.length > 0 &&
				positions.map((_, index) => (
					<div key={index} className="watermark" style={{ top: positions[index].top, left: positions[index].left }}>
						{sessionStorage.getItem("sname")}
					</div>
				))}
		</div>
	);
};

export default Watermark;
